import 'dart:ui';

import 'package:aichat_flutter_wallet/module/module_integral/model/integral_api.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/header/page_header.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../model/integral_model.dart';

class PointsListPage extends StatefulWidget {
  PointsListPage({
    super.key,
  });

  @override
  State<PointsListPage> createState() => _PointsListPageState();
}

class _PointsListPageState extends State<PointsListPage> {

  RefreshController _refreshController =
  RefreshController(initialRefresh: false);
  ScrollController _scrollController = new ScrollController(); //监听下拉框的状态
  List<IntegralRankType> integralRecord = [];
  IntegralRankType userIntegralRecord = IntegralRankType(avatar: '', exchange: '0.00', rank: '11', user_id: '--', nickname: '--', integral: '--');
  int page = 1;
  int size = 10;
  int count = -1;
  bool isLoad = false;
  String _title = '';
  Color _bgColor = Colors.transparent;

  String integralType(int type) {
    switch (type) {
      case 1:
        return 'Sign In Task';
      case 2:
        return 'Beginner Tasks -';
      case 3:
        return 'Daily Tasks -';
      case 4:
        return 'Advanced Tasks -';
      default:
        return '';
    }
  }

  Widget DetailItem(IntegralRankType item, int index, int sort) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          flex: 1,
          child: Row(
            children: [
              Container(
                width: 36.w,
                padding: EdgeInsets.only(left: int.parse(item.rank) < 3 ? 0 : 4.w),
                child: int.parse(item.rank) < 4
                    ? Image.asset(
                        "assets/images/integral/list_${int.parse(item.rank)}.png",
                        width: 36.w,
                        height: 36.w,
                      )
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            'TOP',
                            style: TextStyle(
                                color: Color.fromRGBO(255, 255, 255, .6),
                                fontSize: 12.sp,
                                fontWeight: FontWeight.w700,
                                fontFamily: "_DIN"),
                          ),
                          Text(
                            (int.parse(item.rank) < 10 ? '0' : '') + int.parse(item.rank).toString(),
                            style: TextStyle(
                                color: Color.fromRGBO(255, 255, 255, .6),
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w700,
                                fontFamily: "_DIN"),
                          ),
                        ],
                      ),
              ),
              SizedBox(
                width: 10.w,
              ),
              ClipRRect(
                borderRadius: BorderRadius.circular(21.w),
                child: PublicImage(
                  image: item.avatar,
                  width: 42.w,
                  height: 42.w,
                ),
              ),
              SizedBox(
                width: 10.w,
              ),
              Expanded(
                  flex: 1,
                  child: Text(
                    item.nickname,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(fontSize: 14.sp, fontWeight: FontWeight.w500, color: AppColors.c_DCD7FD),
                  ))
            ],
          ),
        ),
        SizedBox(
          width: 30.w,
        ),
        if (index != 0)
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Text(
                item.integral.toString(),
                style: TextStyle(
                    fontSize: 20.w, fontFamily: "_DIN", fontWeight: FontWeight.w700, color: AppColors.c_white),
              ),
              Text(
                'Claimed KC',
                style:
                    TextStyle(fontSize: 12.sp, fontWeight: FontWeight.w400, color: Color.fromRGBO(255, 255, 255, .6)),
              ),
            ],
          ),
        if (index == 0)
          IntrinsicHeight(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text.rich(
                  TextSpan(children: [
                    TextSpan(
                      text: item.integral.toString(),
                      style: TextStyle(
                          fontSize: 20.w, fontFamily: "_DIN", fontWeight: FontWeight.w700, color: AppColors.c_white),
                    ),
                    WidgetSpan(
                      child: SizedBox(width: 4.w), // 这里放置了一个SizedBox作为间隔
                    ),
                    TextSpan(
                      text: "KC",
                      style: TextStyle(
                          fontSize: 12.w, fontWeight: FontWeight.w400, color: Color.fromRGBO(255, 255, 255, .6)),
                    ),
                  ]),
                ),
                Text(
                  '≈${item.exchange.toString()}kai',
                  style:
                      TextStyle(fontSize: 12.sp, fontWeight: FontWeight.w400, color: Color.fromRGBO(255, 255, 255, .6)),
                ),
              ],
            ),
          )
      ],
    );
  }

  Widget DetailList(BuildContext context, List<IntegralRankType> list,bool isLast, String uid) {
    return ListView.builder(
        padding: EdgeInsets.only(left: 0,right: 0,top: 0,bottom: 15.w),
        itemCount: list.length + 1,
        controller: _scrollController,
        itemBuilder: (BuildContext buildContext, int index) {
          if (index == 0) {
            return Container(
              width: double.infinity,
              height: 200.w,
              color: Colors.transparent,
              margin: EdgeInsets.only(bottom: 15.w),
              child: Stack(clipBehavior: Clip.none, children: [
                Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    child: Image.asset(
                      "assets/images/integral/list_bg.png",
                      width: double.infinity,
                      height: 370.w,
                    ))
              ]),
            );
          }
          else if (index == list.length) {
            IntegralRankType item = list[index - 1];
            return Container(
                height: 70,
                margin: EdgeInsets.only(bottom: 10.w, left: 15.w, right: 15.w),
                padding: EdgeInsets.only(right: 15.w, left: 12.w),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(10.w)),
                    border: Border.all(
                        width: 1,
                        color: item.user_id == uid
                            ? Color.fromRGBO(141, 86, 208, 1)
                            :  Colors.transparent),
                    color: Color.fromRGBO(31, 24, 60, 1),
                    image: index < 4
                        ? DecorationImage(
                        image: AssetImage("assets/images/integral/list_${index}_bg.png"), fit: BoxFit.cover)
                        : null),
                child: DetailItem(item, index, index));

          //     Column(
          //     children: [
          // ,
          //       // SizedBox(height: 7.w,),
          //       // Visibility(
          //       //     visible: isLast,
          //       //     child: Container(
          //       //       padding: EdgeInsets.only(top: 0.w, bottom: 121.w),
          //       //       child:

          //       //     ))
          //     ],
          //   );
          }
          else {
            IntegralRankType item = list[index - 1];
            return Container(
                height: 70,
                margin: EdgeInsets.only(bottom: 10.w, left: 15.w, right: 15.w),
                padding: EdgeInsets.only(right: 15.w, left: 12.w),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(10.w)),
                    color: Color.fromRGBO(31, 24, 60, 1),
                    border: Border.all(
                        width: 1,
                        color: item.user_id == uid
                            ? Color.fromRGBO(141, 86, 208, 1)
                            :  Colors.transparent),
                    image: index < 4
                        ? DecorationImage(
                            image: AssetImage("assets/images/integral/list_${index}_bg.png"), fit: BoxFit.cover)
                        : null),
                child: DetailItem(item, index, index));
          }
        });
  }

  @override
  void initState() {
    super.initState();
    getIntegralRecord();
    //触底加载
    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        // getIntegralRecord();
      }
      if (_scrollController.position.pixels != 0 && _title == '') {
        setState(() {
          _title = 'Points Leaderboard';
          _bgColor = Color.fromRGBO(40, 16, 79, 1);
        });
      }
      if (_scrollController.position.pixels == 0 && _title != '') {
        setState(() {
          _title = '';
          _bgColor = Colors.transparent;
        });
      }
    });
  }

  @override
  void dispose() {
    /// 取消路由订阅
    _refreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }



  Future getIntegralRecord() async {
    try {
      if (isLoad || (count < 10 && count != -1)){
        if((count < 10 && count != -1)){
          _refreshController.loadComplete();
        }
        return;
      };
      isLoad = true;
      IntegralApi.getIntegralRank(page: page).then((resp){
        if(resp == null){
          return;
        }
        integralRecord = [...integralRecord, ...resp.rank_list];
        if(resp.user_rank != null  ){
          if(resp.user_rank?.user_id != '0' ){
            userIntegralRecord = resp.user_rank!;
          }
        }
        if(int.parse(resp.count) >= 0){
          count = int.parse(resp.count);
        }
        isLoad = false;
        page++;
        _refreshController.loadComplete();
        if (mounted) { setState(() {});}
      }).onError((error, stackTrace) {
        isLoad = false;
        _refreshController.loadComplete();
        if (mounted) { setState(() {});}
      });
    } catch (e) {
      _refreshController.loadComplete();
      kaiPrint("getIntegralRecord $e");
    }
  }

  Widget bottomControl() {
    return Padding(
        padding: EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom + 0),
        child: Container(
            width: double.infinity,
            height: 101.w,
            alignment: Alignment.topCenter,
            padding: EdgeInsets.fromLTRB(31.w, 13.w, 31.w, 40.w),
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage("assets/images/integral/list_me.png"), fit: BoxFit.cover),
            ),
            child: DetailItem(userIntegralRecord, 0, 1))
    );
  }

  void _onLoading() {
    getIntegralRecord();
  }

  @override
  Widget build(BuildContext context) {
    final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
    return Scaffold(
        backgroundColor: Color.fromRGBO(16, 17, 34, 1),
      appBar: PageHeaderCom(
        showBottomBorder: false,
        bgColor: _bgColor,
        titleColor:Colors.white,
        backIcon: Image.asset(
          'assets/images/integral/list_back.png',
          width: 20.w,
          height: 20.w,
        ),
        title: _title, // 移除AppBar底部的阴影
      ),
      extendBodyBehindAppBar: true,
      body: SmartRefresher(
        enablePullUp: true,
        enablePullDown: false,
        onLoading: _onLoading,
        controller: _refreshController,
        footer: CustomFooter(
          builder: (BuildContext ctx,LoadStatus? mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body = Text(
                'Already at the bottom',
                textAlign: TextAlign.center,
                style: TextStyle(color: AppColors.c_35355B, fontSize: 12, fontWeight: FontWeight.w400),
              );
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("Load Failed!Click retry!",textAlign: TextAlign.center,
                style: TextStyle(color: AppColors.c_35355B, fontSize: 12, fontWeight: FontWeight.w400),);
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("release to load more",textAlign: TextAlign.center,
                style: TextStyle(color: AppColors.c_35355B, fontSize: 12, fontWeight: FontWeight.w400),);
            }
            else{
              body = Text(
                'Already at the bottom',
                textAlign: TextAlign.center,
                style: TextStyle(color: AppColors.c_35355B, fontSize: 12, fontWeight: FontWeight.w400),
              );
            }
            return Container(
              height: 22.w,
              child: Center(child:body),
            );
          },
        ),
        child: DetailList(context, integralRecord ,  (count < 10 && count != -1),userId),
      ),
      bottomNavigationBar: bottomControl()
    );
  }
}
